<template>
  <div class="purchase-products-list-component-page">
    <div class="block">
      <header class="block-header">
        <h2 class="required">
          <slot />
        </h2>
      </header>
      <section style="height:400px;display:flex;flex-direction:column;">
        <div style="margin-bottom: 15px;">
          <span
            v-if="
              stepOneFormData.return_type_name === '2' ||
                !stepOneFormData.return_type_name ||
                stepOneFormData.busModel === '1'
            "
            style="float: left"
          >
            <el-button type="primary" @click="onOpenImportProduct">
              模板导入产品
            </el-button>
            <el-divider direction="vertical" />
            <el-button type="text" @click="onGetProductTemplate">
              模板下载
            </el-button>
          </span>
          <span class="right" style="float: right">
            <slot name="btn" />
            <el-button type="primary" @click="onOpenProductDialog">
              添加退货产品
            </el-button>
          </span>
        </div>
        <el-editable
          ref="productsTableList"
          :columns="
            stepOneFormData.return_type_name === '2' ||
            !stepOneFormData.return_type_name ||
            stepOneFormData.busModel === '1'
              ? SELECTED_PRODUCTS_COLUMNS
              : ORIGINAL_SELECTED_PRODUCTS_COLUMNS
          "
          :payload="payload_products"
          :need-pagination="true"
          height="200"
          @reload="reloadData"
        >
          <template #default-index="{ $index }"> {{ $index + 1 }}</template>
          <template #default-returnCount="{ row, $index }">
            <div>
              <el-input-number
                v-model="row.productCount"
                :step="1"
                step-strictly
                size="small"
                :min="1"
                :max="Math.floor(row.returnCount)"
                @change="onChangeCount(row, $index)"
              />
              <span style="margin-left:10px;color:red;"
                >可退量{{ row.returnCount | decimalToInteger }}</span
              >
            </div>
          </template>
          <template #default-opt="{ row, $index }">
            <a href="javascript:;" @click="onDeleteProduct(row, $index)"
              >删除</a
            >
          </template>
          <!-- 给创建报台用的表格内表单 -->
        </el-editable>
      </section>
    </div>
    <upload
      ref="upload"
      :params="stepOneFormData"
      @complete="getUploadProducts"
    />
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import { urlDownload } from '@const/utils';
import { computeRate, formatPrice } from '@const/filter';
// eslint-disable-next-line import/named
import { ProductAddDialogService } from './product-dialog/product-add.dialog.module';
// eslint-disable-next-line import/extensions
import * as CONSTS from './index.const.js';
// eslint-disable-next-line import/extensions
import { IndexService } from './index.service.js';
// eslint-disable-next-line import/extensions
import upload from './upload';

const service = new IndexService();
export default {
  components: {
    ElEditable,
    upload
  },
  filters: {
    decimalToInteger(num) {
      return parseFloat(num);
    }
  },
  inject: ['templateDownLoad'],
  props: {
    searchLabel: {
      type: String,
      default: '原采购单号'
    },
    stepOneFormData: {
      type: Object,
      default() {}
    },
    products: {
      type: Array,
      default() {}
    },
    type: {
      type: String,
      default: 'default'
    },
    operationType: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '添加销售产品'
    },
    // 其实这个字段判断跟title类似
    isOriginal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ...CONSTS,
      productsData: [],
      payload_products: {},
      pager: {
        number: 1,
        size: 20
      },
      // 由于更新数量的动态性，下标的切换要同步。故这样搞
      index: {
        start: 1,
        end: 1
      }
    };
  },
  computed: {
    productAddDialogService() {
      return new ProductAddDialogService(this.$axios, this.$store, {
        type: this.type
      });
    },
    isExProductsExist() {
      return !!this.stepOneFormData.exchange_goods?.length;
    }
  },
  watch: {
    products: {
      handler(val) {
        if (val !== undefined) {
          this.productsData = val;
          const startIndex = (this.pager.number - 1) * this.pager.size;
          const endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(
            this.productsData,
            this.pager,
            startIndex,
            endIndex
          );
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getUploadProducts(payload) {
      const loadProductList = payload;
      if (loadProductList.length > 0) {
        this.updateProductData(payload, true);
      }
    },
    // 前端分页逻辑
    reloadData(pager) {
      const startIndex = (pager.number - 1) * pager.size;
      const endIndex = pager.number * pager.size;
      this.payload_products = service.getPayload(
        this.productsData,
        pager,
        startIndex,
        endIndex
      );
      this.pager = pager;
    },
    onDeleteProduct(row, index) {
      if (this.isExProductsExist) {
        this.handlerMiddleEvent(
          () => {
            // 如果确定，那么清空换货数据并删除该条数据
            this.realDeleteItem(row, index);
            this.$emit('clearExchangeGoods');
          }
          // 如果是取消，无响应即可
        );
      } else {
        // 如果没有换货数据，正常删除
        this.realDeleteItem(row, index);
      }
    },
    realDeleteItem(row, index) {
      let startIndex = null;
      let endIndex = null;
      startIndex = (this.pager.number - 1) * this.pager.size;
      endIndex = this.pager.number * this.pager.size;
      this.productsData.splice(startIndex + index, 1);
      this.payload_products = service.getPayload(
        this.productsData,
        this.pager,
        startIndex,
        endIndex
      );
      if (this.payload_products.content.length === 0) {
        // 如果当前获取的内容为空，那么要重新获取一下数据
        this.pager.number -= 1;
        if (this.pager.number <= 0) this.pager.number = 1;
        startIndex = (this.pager.number - 1) * this.pager.size;
        endIndex = this.pager.number * this.pager.size;
        this.payload_products = service.getPayload(
          this.productsData,
          this.pager,
          startIndex,
          endIndex
        );
      }
      this.$emit('update:products', this.productsData);
    },
    onChangeCount(row, idx) {
      const newRow = row;
      if (newRow.productCount >= newRow.returnCount) {
        newRow.productCount = newRow.returnCount;
      }
      if (!newRow.productCount) {
        this.$nextTick(() => {
          newRow.productCount = 1;
        });
      }
      if (this.isExProductsExist) {
        this.handlerMiddleEvent(
          () => {
            // 如果确定，那么清空换货数据并同步静态数据
            newRow.staticProductCount = newRow.productCount;
            this.$emit('clearExchangeGoods');
          },
          // 如果是取消，那么就把静态数量赋值给productCount
          () => {
            newRow.productCount = newRow.staticProductCount;
          }
        );
      } else {
        // 如果没有换货数据，同步静态数量
        newRow.staticProductCount = newRow.productCount;
      }
      this.calcCurTotalFee(newRow, idx);
      this.$emit('update:products', this.productsData);
    },
    onChangeReferencePrice(row, idx) {
      this.calcCurTotalFee(row, idx);
    },
    calcCurTotalFee(row) {
      const newRow = row;
      newRow.totalFee = formatPrice(
        computeRate(row.referencePrice, row.productCount),
        2
      );
    },
    onOpenProductDialog() {
      if (this.isExProductsExist) {
        this.handlerMiddleEvent(() => {
          this.$emit('clearExchangeGoods');
          this.openReturnProductsList();
        });
      } else {
        this.openReturnProductsList();
      }
    },
    openReturnProductsList() {
      console.log(this.stepOneFormData, '291------------');
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      this.productAddDialogService
        .create({
          title: this.title,
          query: {
            operationType: this.operationType,
            formData: this.stepOneFormData,
            searchLabel: this.searchLabel,
            isOriginal: this.isOriginal
          },
          confirmButtonClickHandler: (data = {}) => {
            data.forEach(element => {
              this.$set(element, 'productCount', 1);
              this.$set(
                element,
                'totalFee',
                formatPrice(
                  computeRate(element.referencePrice, element.productCount),
                  2
                )
              );
            });
            this.updateProductData(data);
          }
        })
        .mount();
    },
    updateProductData(data, isImport) {
      this.productsData = service.reConcatSelectData(
        data,
        this.productsData,
        'mixsIds',
        isImport
      );
      const startIndex = (this.pager.number - 1) * this.pager.size;
      const endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(
        this.productsData,
        this.pager,
        startIndex,
        endIndex
      );
      this.$emit('update:products', this.productsData);
    },
    onOpenImportProduct() {
      if (this.isExProductsExist) {
        this.handlerMiddleEvent(() => {
          this.$refs.upload.dialog_visible = true;
          this.$emit('clearExchangeGoods');
        });
      } else {
        this.$refs.upload.dialog_visible = true;
      }
    },
    handlerMiddleEvent(resolve = () => {}, reject = () => {}) {
      this.$confirm(
        '若修改退货产品，添加的新换产品将会清空',
        '确认修改退货产品么？',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(resolve)
        .catch(reject);
    },
    onGetProductTemplate() {
      urlDownload(this.templateDownLoad);
    }
  }
};
</script>
<style lang="less" scoped>
// .purchase-products-list-component-page {
//   .block {
//     section {
//       .el-editable {
//         .el-table--scrollable-x .el-table__body-wrapper {
//           height: 229px;
//         }
//       }
//     }
//   }
// .el-editable .el-table--scrollable-x .el-table__body-wrapper {
//   height: 229px;
// }
// }
</style>
